<template>
  <div class="header">
    <div class="header-pos" @click="pickCity">
      <div class="pos-info">
        {{ userPosition ? userPosition : "正在定位..." }}
      </div>
      <div class="city-select"></div>
    </div>
    <slot name="headerSlot"></slot>
  </div>
</template>

<script>
import txMap from "../../static/lib/qqmap-wx-jssdk.min.js";
let map = new txMap({
  key: "ET3BZ-D7UK6-C7ASK-EDTA4-FVS5H-WEFBL",
});
export default {
  data() {
    return {
      userPosition: "", // 城市名
      active: 1,
      systemInfoSync: "",
    };
  },
  created() {
    // 先判断是否有权限
    wx.getSetting({
      success: (res) => {
        console.log(res.authSetting);
        if (res.authSetting["scope.userLocation"]) {
          // 有则直接获取数据
          this.getUserLocation();
        } else {
          // 没有就先获取权限
          this.getAuthorize();
        }
      },
    });
    // 获取当前设备型号和系统版本号
    this.systemInfoSync = wx.getSystemInfoSync();
    console.log(this.systemInfoSync);
  },
  methods: {
    // .获取当前位置的经纬度，通过腾讯位置信息将经纬度转换成城市中文名称
    getUserLocation() {
      wx.getLocation({
        success: (res) => {
          map.reverseGeocoder({
            location: {
              latitude: res.latitude,
              longitude: res.longitude,
            },
            success: (res) => {
              console.log(res);
              this.userPosition = res.result.address_component.city.split('市')[0];
            },
            // 位置获取失败提示
            fail: (err) => {
              console.log(err);
              this.userPosition = '定位失败'
              this.$emit("locationPopupHandel");
            },
          });
        },
      });
    },
    getAuthorize() {
      wx.authorize({
        scope: "scope.userLocation",
        success: () => {
          this.getUserLocation();
        },
        // 当用户第一次拒绝授权之后，就不会出现弹窗，所以这里需要自己处理
        fail: () => {
          console.log("33333");
          this.getAuthorizeAgen();
        },
      });
    },
    getAuthorizeAgen() {
      wx.authorize({
        scope: "scope.userLocationBackground",
        success: (res) => {
          this.getUserLocation();
        },
        fail: () => {},
      });
    },
    // 城市选择
    pickCity() {
      wx.navigateTo({ url: `../citySelect/main?userPosition=${this.userPosition}` });
    }
  },
};
</script>

<style  lang="css" scoped>
.header {
  position: fixed;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
  height: 44px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 15px;
  z-index: 1;
}
.header-pos {
  width: 80px;
  height: 44px;
  display: flex;
  align-items: center;
}
.pos-info {
  font-size: 12px;
}
.city-select {
  width: 0;
  height: 0;
  border: 4px solid #b0b0b0;
  border-left-color: transparent;
  border-right-color: transparent;
  border-bottom-color: transparent;
  display: inline-block;
  margin-left: 4px;
  margin-top: 5px;
}
</style>